﻿using System;
using System.Windows.Forms.VisualStyles;
using EzDesk.DesktopClient.Command;
using EzDesk.DesktopClient.Event;
using EzDesk.DesktopClient.Model;
using EzDesk.DesktopClient.MVVMEnhance;
using EzDesk.DesktopClient.PopupModule.ViewContract;
using EzDesk.DesktopClient.UtilityView.ViewModel;
using EzDesk.Generic;

namespace EzDesk.DesktopClient.PopupModule.ViewModel
{
    public interface INotificationPopupViewModel:IFeedItemViewModel<INotificationPopupView>
    {
        void DisableNotification();

        event EventHandler OnClosing;

        new INotificationPopupViewModel SetModel(Feed feed);
    }

    public class NotificationPopupViewModel :
        FeedItemViewModel<INotificationPopupView, INotificationPopupViewModel>, 
        INotificationPopupViewModel
    {
        public event EventHandler OnClosing;
        public DelegateCommand CloseWindowCommand { get; private set; }

        private void InvokeClose(EventArgs e)
        {
            EventHandler handler = OnClosing;
            if (handler != null) handler(this, e);
        }

        public NotificationPopupViewModel(INotificationPopupView notificationPopupView)
        {
            this.View = notificationPopupView;
            InitLocalEvent();
        }

        public new INotificationPopupViewModel SetModel(Feed feed)
        {
            base.SetModel(feed);
            return this;
        }


        private void InitLocalEvent()
        {
            View.OnNavigate += OnNavigate;
            View.OnWindowClosing += (o, e) =>
                    {
                        InvokeClose(null);
                        View = null;
                    };

            CloseWindowCommand = new DelegateCommand(() =>
            {
                IsRead = true;
                UpdateDataManagement.Instance.UpdateFeedStatusInCache(FeedModel);
                View.CloseNotificationView();
            });
        }

        public void DisableNotification()
        {
            this.View.CloseNotificationView();
        }

        private void OnNavigate(object sender, GenericEventArg<string> e)
        {
            this.IsRead = true;
            UpdateDataManagement.Instance.UpdateFeedStatusInCache(FeedModel);
            FunctionNavigateEvent.Instance.Publish(new FunctionNavigateArgs { Url = e.Value });
            View.CloseNotificationView();
        }


        protected override void OnDispose()
        {
            CloseWindowCommand = null;
            base.OnDispose();
        }
    }
}